from flask import render_template, request, jsonify, current_app, session
from info.models import Category, News, User
from . import home_blue
from ...constants import HOME_PAGE_MAX_NEWS
from info.response_code import RET,error_map
# 1.首页展示渲染
@home_blue.route("/")
def index():
    # 1.新闻分类获取
    category_list = Category.query.all()
    # 2.用户登录状态的判断
    user_id = session.get("user_id")
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except BaseException as e:
            current_app.logger.error(e)
    user = user.to_dict() if user else None
    # 3.新闻点击排行的获取
    news_click_list = News.query.order_by(News.clicks).limit(10).all()
    return render_template('news/index.html', data = {"category_list":category_list,
                                                      "news_click_list":news_click_list,
                                                      "user_info": user
                                                      })
# 2.新闻列表接口
@home_blue.route("/news_list")
def news_list():
    # 入参
    cid = request.args.get("cid")
    cur_page = request.args.get("page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)  # 每页条数

    cid = int(cid)
    cur_page = int(cur_page)
    per_count = int(per_count)

    filter_list = [News.status == 0]
    if cid != 1:
        filter_list.append(News.category_id == cid)
    pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(page=cur_page,per_page=per_count)
    data = {
        "news_dict_list": [news.to_basic_dict() for news in pn.items],
        "total_page": pn.pages
    }
    # 将新闻数据以json返回
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)


# 3.设置网站小图标
@home_blue.route('/favicon.ico')
def favicon():
    # 使用send_static_file来返回静态文件， 默认的静态文件访问也是调用该方法
    return current_app.send_static_file("news/favicon.ico")